<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品促销标签类
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   create by allen.qiang
 * @version 1.0
 */

class goodsPromotion {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }
    
     /**
     * 商品基本促销标签查询
     */
    public function searchPromotionTag( &$arg_array ) {
    
    	//sql字符串
    	$sql = '';
    
    	//参数类型字符串
    	$params_type = '';
    
    	//参数值数组
    	$params_array = array();
    
    	//促销标签ID
    	if (isset($arg_array['tagID']) && is_numeric($arg_array['tagID'])) {
    		$sql .= ' AND tagID = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['tagID'];
    	}
    
    	//促销标签名称
    	if (isset($arg_array['tagName']) && !empty($arg_array['tagName'])) {
    		$sql .= ' AND tagName LIKE ?';
    		$params_type .= 's';
    		$params_array[] = '%'.$arg_array['tagName'].'%';
    	}
    	
    	//使用标志
    	if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) && in_array($arg_array['useFlg'],array(0,1))) {
    		$sql .= ' AND useFlg = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['useFlg'];
    	}
    	
    	//扩展
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
        	$sql .= $arg_array['extend'];
        }
    
    	if ($sql) {
    		$sql = ' WHERE ' . substr($sql, 4);
    	}
    
    	try {
    
    		if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {
    
    			//统计促销行数
    			$search_sql  = 'SELECT COUNT(*) AS count FROM goods_promotion_tag ' . $sql;
    			$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    			$item_count  = $count_array[0]->count;
    			if ($item_count == 0) {
    				$arg_array['count'] = 0;
    				return null;
    			}
    
    			$arg_array['count'] = $item_count;
    
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
    
    			//分页
    			if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
    				$arg_array['page'] = 1;
    
    			$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
    
    		} else {
    
    			$arg_array['count'] = 0;
    
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
    
    		}
    
    		//查询商品促销信息
    		$search_sql = 'SELECT * FROM goods_promotion_tag' . $sql;
    		$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    
    		if ($temp_item_array) {
    			foreach($temp_item_array as &$item) {
    				$item_array[] = array(
						'tagID'	=> $item->tagID,
						'image' 	=> G_IMAGE_URL . 'goods/' . $item->image,
						'orgitalImage' => $item->image,
						'tagName' 	=> $item->tagName,
						'sortOrder'	=> $item->sortOrder,
						'useFlg'	=> $item->useFlg
    				);
    			}
    		}
    
    		return isset($item_array) ? $item_array : null;
    
    	} catch (Exception $e) {
    
    		error_log($e->getMessage());
    		return null;
    
    	}
    }

    /**
     * 获取原材料的最大序号
     */
    public function maxSort() {

        $maxSort = $this->dbca->stmt_query('SELECT MAX(sortOrder) AS maxSort FROM goods_promotion_tag');

        $maxSort = $maxSort[0]->maxSort;

        return $maxSort;

    }

    /**
     * 使用标志
     */
    public function changeUse($tagID,$useFlg) {

        try{

            //检测参数
            $goods_promotion = new entity('goods_promotion_tag');
            $goods_promotion->tagID = $tagID;
            if (!$this->dbca->fetch($goods_promotion)) {
                throw new Exception( '查无此商品促销标签' , 404 );
            }

            if (!is_numeric($useFlg) || !in_array($useFlg,array(0,1))) {
                throw new Exception( '使用状态不正确' , 404 );
            }

            //多页面操作问题
            if ($useFlg == 1 && $goods_promotion->useFlg == 1) {
                throw new Exception( '商品促销标签已经启用,请刷新页面' , 400 );
            }

            if ($useFlg == 0 && $goods_promotion->useFlg == 0) {
                throw new Exception( '商品促销标签已经禁用,请刷新页面' , 400 );
            }

            //使用状态修改
            $goods_promotion->useFlg = $useFlg;

            if (!$this->dbca->save($goods_promotion)) {
                throw new Exception( '使用状态修改失败' , 400 );
            }

            return array( 'code' => 200 , 'message' => 'ok' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                return array( 'code' => 500 , 'message' => '系统错误' );
            }

        }

    }

    /**
     * 删除
     */
    public function delgoodsPromotion($tagID) {

        try{

            $this->dbca->beginTransaction();

            //循环删除
            $j = count($tagID);
            for($i=0;$i<$j;$i++){
                $goods_promotion = new entity('goods_promotion_tag');
                $goods_promotion->tagID = $tagID[$i];
                if (!$this->dbca->fetch($goods_promotion)) {
                    throw new Exception('要删除的商品促销标签不存在',404);
                } else {
                    if (!$this->dbca->delete($goods_promotion)) {
                        throw new Exception('删除商品促销标签失败',400);
                    }
                }
            }

            $this->dbca->commit();

            return array( 'code' => 200 , 'message' => 'ok' );

        } catch (Exception $e) {

            $this->dbca->rollback();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                return array( 'code' => 500 , 'message' => '系统错误' );
            }

        }
    }

    /**
     * 保存、修改
     */
    public function saveGoodsPromotion($arg_array) {

        /**
         * 检查参数
         */
        //定义错误变量
        $error_msg = '';

        if (isset($arg_array['tagID']) && !empty($arg_array['tagID'])) {
            $tagID = $arg_array['tagID'];
        } else {
            $tagID = 0;
        }

        if (isset($arg_array['tagName']) && !empty($arg_array['tagName'])) {
            $tagName = $arg_array['tagName'];
        } else {
            $error_msg += '未输入促销标签名称<br />';
        }

        if (isset($arg_array['sortOrder']) && is_numeric($arg_array['sortOrder'])) {
            $sortOrder = $arg_array['sortOrder'];
        } else {
            $error_msg += '请输入正确的排序序号<br />';
        }

        if (isset($arg_array['hidImg']) && !empty($arg_array['hidImg'])) {
            $image = $arg_array['hidImg'];
        } else {
            $error_msg += '原材料图片未上传<br />';
        }

        if ($error_msg != '') {
            return array( 'code' => 400 , 'message' => $error_msg );
        }

        /**
         * 数据存入数据库
         */
        try{
            global $G_PGLOB;

            $this->dbca->beginTransaction();

            //商品原材料数据
            $goods_promotion = new entity('goods_promotion_tag');

            $flg = 0;   //添加的标志

            if ($tagID > 0) {
                $goods_promotion->tagID = $tagID;
                if (!$this->dbca->fetch($goods_promotion)) {
                    return array( 'code' => 400 , 'message' => '商品促销标签不存在' );
                }

                //商品促销标签名称 序号不能重复
                $promotionArray = $this->dbca->stmt_query('SELECT tagName,sortOrder FROM goods_promotion_tag WHERE tagID != ?','i',$tagID);

                $flg = 1;   //修改的标志
            } else {
                //商品促销标签名称 序号不能重复
                $promotionArray = $this->dbca->stmt_query('SELECT tagName,sortOrder FROM goods_promotion_tag');
                $goods_promotion->creator = $G_PGLOB->currentUserID;
            }

            //商品促销标签名称 序号不能重复
            $msg = '';
            if($promotionArray){
                foreach ($promotionArray as $v) {
                    if ($v->sortOrder == $sortOrder) {
                        $msg.= '排序序号已存在<br />';
                    }
                    if ($v->tagName == $tagName) {
                        $msg.= '促销标签名称已存在<br />';
                    }
                }
            }

            if (!empty($msg)) {
                throw new Exception($msg,400);
            }

            $save_dir = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/goods/promotionTag/';
            if (!@file_exists($save_dir)) {
                mkdir($save_dir, 0777, true);
            }
            //截取图片名称
            $imageName = substr($image, -23);
            copy(G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/kindeditor/'.date('Ymd').'/'.$imageName,G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/goods/promotionTag/'.$imageName);
            $goods_promotion->tagName   	= $tagName;
            $goods_promotion->image     	= 'promotionTag/'.$imageName;
            $goods_promotion->sortOrder   	= $sortOrder;
            $goods_promotion->useFlg      	= 1;

            if (!$this->dbca->save($goods_promotion)) {
                throw new Exception('商品原材料数据保存失败',400);
            }

            $this->dbca->commit();

            return array( 'code' => 200 , 'message' => '数据保存成功' , 'data' => $flg );

        } catch(Exception $e) {

            $this->dbca->rollback();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500 , 'message' => '系统错误' , 'data' => $flg );
            }

        }
    }

    /**
     * 查询商品和原材料信息映射关系
     * create by allen.qiang
     * @param $arg_array 参数数组
     * @return array|null
     */
    public function searchMaterRelation( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        //原材料ID
        if (isset($arg_array['materID']) && is_numeric($arg_array['materID'])) {
            $sql .= ' AND materID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materID'];
        }

        //扩展
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_mater_relation ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_mater_relation ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'postID' => $item->postID,
                    'materID' => $item->materID,
                    'materName' => $item->materName,
                    'image' => set_goods_img_link($item->image),
                    'orgitalImage' => $item->image,
                    'sortOrder' => $item->sortOrder
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

}